package com.base.controller.coupon_api;

import com.alibaba.fastjson.JSONObject;
import com.base.controller.api.RedisCacheManager;
import com.base.helper.VosHelper;
import com.base.po.coupon_new.CouponGoodsNew;
import com.base.po.coupon_sdk.CouponConfigNew;
import com.base.po.coupon_sdk.CouponInfoUtilNew;
import com.base.po.coupon_sdk.GetOrderUUID;
import com.base.po.param.NetState;
import com.base.po.param.VosModelList;
import com.base.po.voip.Subscribers;
import com.base.po.voip.Users;
import com.base.po.voip_coupon.CouponBrand;
import com.base.service.COUPON.*;
import com.base.service.SubscribersService;
import com.base.service.UsersService;
import com.base.utils.GsonUtil;
import com.base.utils.Page;
import com.beust.jcommander.internal.Lists;
import com.beust.jcommander.internal.Maps;
import lombok.extern.log4j.Log4j;
import org.apache.commons.lang3.StringUtils;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.web.bind.annotation.RequestMapping;
import org.springframework.web.bind.annotation.RequestMethod;
import org.springframework.web.bind.annotation.RestController;

import java.io.UnsupportedEncodingException;
import java.math.BigDecimal;
import java.util.List;
import java.util.Map;

/**
 * 365优惠券 传入CouponInfo Brands
 *
 * @author K
 */
@Log4j
@RestController
@RequestMapping("/coupon")
public class CouponInfoController {
    private final CouponCategoryService couponCategoryService;
    private final CouponBrandService couponBrandService;
    private final CouponGoodsNewService couponGoodsNewService;
    private final RedisCacheManager redisCacheManager;
    private final SubscribersService subscribersService;
    private final CouponOrderNewSubService couponOrderNewSubService;
    private final CouponOrderNewService couponOrderSubService;
    private final UsersService usersService;

    @Autowired
    public CouponInfoController(CouponGoodsNewService couponGoodsNewService, CouponCategoryService couponCategoryService, CouponBrandService couponBrandService, RedisCacheManager redisCacheManager, SubscribersService subscribersService, CouponOrderNewSubService couponOrderNewSubService, CouponOrderNewService couponOrderSubService, UsersService usersService) {
        this.couponGoodsNewService = couponGoodsNewService;
        this.couponCategoryService = couponCategoryService;
        this.couponBrandService = couponBrandService;
        this.redisCacheManager = redisCacheManager;
        this.subscribersService = subscribersService;
        this.couponOrderNewSubService = couponOrderNewSubService;
        this.couponOrderSubService = couponOrderSubService;
        this.usersService = usersService;
    }
    @RequestMapping(value = "/getGoodsNews", method = RequestMethod.POST)
    public NetState getGoodsNews(String brandId, Page page, String parentid, String mobile) {
        List<CouponGoodsNew> couponGoodsNewList = couponGoodsNewService.selectAllDetail(null, parentid, brandId);
        couponGoodsNewList.forEach(item -> {
            Integer stock = 0;
            try {
                String result = CouponInfoUtilNew.getStock(item.getGoodsNo());
                JSONObject jsonObject = JSONObject.parseObject(result);
                stock = jsonObject.getString("stock_num") == null ? 0 : Integer.parseInt(jsonObject.getString("stock_num"));
                item.setStock(stock);
            } catch (Exception e) {
                e.printStackTrace();
            }

        });
        return new NetState("成功", NetState.SUCCESS_CONN, couponGoodsNewList);
    }

    @RequestMapping(value = "/getGoodsBranch", method = RequestMethod.POST)
    public NetState getGoodsBrancch(String parentid, String mobile, String topId, Integer sort, Page page) {
        List<CouponBrand> couponBrandList = couponBrandService.selectAll(null, null, null, null, 1);
        Integer size = couponBrandList.size();
        Map<String, Object> map = Maps.newHashMap();
        map.put("data", couponBrandList);
        map.put("size", size);
        return new NetState("查询成功", NetState.SUCCESS_CONN, map);
    }


    @RequestMapping(value = "/recordUserBuy", method = RequestMethod.POST)
    public NetState payUrl(String goodsId, Integer count, String redirectUrl, String usermobile, String parentid) {

        String batchNo = GetOrderUUID.getOrderIdByUUId();
        Subscribers sub = subscribersService.selectBySubscribers(usermobile, parentid);
        CouponGoodsNew couponGoodsNew=couponGoodsNewService.selectCouponGoodsNewByGoodsNo(goodsId);
        if (couponGoodsNew == null ){
            return new NetState(NetState.NEED_SYSTEM_PARAM, "商品不存在");
        }
        if (sub == null) {
            return new NetState(NetState.NEED_SYSTEM_PARAM, "用户不存在");
        }

        Users agent=usersService.selectByPrimaryKey(sub.getParentid());

        Subscribers user=sub;

        BigDecimal money=new BigDecimal(0);

        BigDecimal compareMoney=couponGoodsNew.getOfficialPrice().subtract(couponGoodsNew.getSellPrice());

        try {
            // TODO 暂时配注
            String userR = VosHelper
                    .GetVosAccount("{accounts:['" + agent.getAgentprefix() + user.getMobile() + "']}");
            if (userR != null) {
                VosModelList shareUserR1 = GsonUtil.getObject(userR, VosModelList.class);
                if (shareUserR1.retCode == 0) {
                    money = shareUserR1.infoCustomers[0].getMoney();
                }
            }
        } catch (Exception e) {
           log.warn(e);
        }
         if(agent.getId().equals("13715e2af9b24f55ab24773101688490") || agent.getId().equals("24bc36812eed4772ae7a18efab0e3048")){
            //不做处理  如果是团拼宝
        }else  {
             if (money.compareTo(compareMoney)<=0){
                 return new NetState(NetState.FEAILED, "账户余额不足");
             }
         }
        String result = null;
        try {
            result = CouponInfoUtilNew.getPayUrl(goodsId, count, batchNo, CouponConfigNew.notify_url, redirectUrl, CouponConfigNew.order_change_notify_url);
        } catch (UnsupportedEncodingException e) {
            e.printStackTrace();
            return new NetState(NetState.SYSTEM_ERROR, "系统异常");
        }
        JSONObject resultData = JSONObject.parseObject(result);
        if (!resultData.getString("code").equals("200")){
            return new NetState(NetState.SYSTEM_ERROR, "库存不足");
        }
        redisCacheManager.set("QY:" + batchNo, sub.getId(), 7200);
        Map<String, Object> resutMap = Maps.newHashMap();
        resutMap.put("code", resultData.getString("code"));
        resutMap.put("jumpUrl", resultData.getString("cashier_url"));
        resutMap.put("message", resultData.getString("message"));
        return new NetState("成功", NetState.SUCCESS_CONN, resutMap);
    }

    @RequestMapping(value = "/getOrderBuySub", method = RequestMethod.POST)
    public NetState getOrderBuySub(String subid, Page page, Integer status) {
        Integer pageOld = page.getCurrentPageNo();
        Subscribers sub = subscribersService.selectByPrimaryKey(subid);
        if (sub == null) {
            return new NetState(NetState.SUCCESS_CONN, "用户ID传入错误");
        }
        Integer count = couponOrderSubService.countALLLeftJoin(sub.getParentid(), sub.getMobile(), status);

        page.setRecordTotal(count);

        if (pageOld > page.getCurrentPageNo()) {
            return new NetState(NetState.SUCCESS_CONN, "成功");
        }
        List<Map> result = Lists.newArrayList();
        result = couponOrderSubService.selectALLLeftJoin(page, sub.getParentid(), sub.getMobile(), status);

        result.forEach(item->{
           String goodsno= item.get("goods_no").toString();
           CouponGoodsNew couponGoodsNew=couponGoodsNewService.selectCouponGoodsNewByGoodsNo(goodsno);
           if (couponGoodsNew != null){
               item.put("imgUrl",couponGoodsNew.getImgUrl());
           }
        });

        return new NetState("成功", NetState.SUCCESS_CONN, result);
    }

    @RequestMapping(value = "/getGoodsDetails", method = RequestMethod.POST)
    public NetState getOrderBuySub(String goodsNo) {
        if (StringUtils.isEmpty(goodsNo)){
            return new NetState(NetState.FEAILED,"参数缺失");
        }
        CouponGoodsNew couponGoodsNew=couponGoodsNewService.selectCouponGoodsNewByGoodsNo(goodsNo);
        return new NetState("成功",NetState.SUCCESS_CONN,couponGoodsNew);
    }
}
